package com.caifenglin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {

	private static final Logger log = LoggerFactory.getLogger(HelloWorld.class);
	
	public static void main(String[] args) {
		log.info("我们正在测试log4j········");
		/**
		 *  1.获取安全管理器
		 *  
		 *  2.获取用户
		 *  
		 *  3.用户登录验证
		 *  
		 *  4.权限管理
		 *  
		 *  5.角色管理
		 *  
		 *  6.session
		 *  
		 */
		
		// 1.获取安全管理器
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager securityManager = factory.getInstance();
		// 2.需要设置安全管理器
		SecurityUtils.setSecurityManager(securityManager);
		
		// 3.获取Subject对象，即将登录的用户
		Subject currentUser = SecurityUtils.getSubject();
		
		Session session = currentUser.getSession();
		
		session.setAttribute("name", "蔡锋林");
		
		String value = (String)session.getAttribute("name");
		
		if(value != null) {
			log.info("shiro已经帮我们获取到session回话对象中的值："+value);
		}
		
		if(currentUser.isAuthenticated() == false) {
			// UsernamePasswordToken
			UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
			token.setRememberMe(true);
			try {
				currentUser.login(token);
				log.info("用户名和密码正确，登录成功！");
			} catch (UnknownAccountException e) {
				log.info("账户不存在");
				// e.printStackTrace();
			} catch (IncorrectCredentialsException e) {
				log.info("密码错误");
			} catch (LockedAccountException e) {
				log.info("用户已经锁死");
			} catch (AuthenticationException e) {
				log.info("认证异常");
			}
		}
		
		if(currentUser.hasRole("goodguy")) {
			log.info("拥有指定角色");
		} else{
			log.info("不拥有指定角色");
		}
		
		// Subject:isPermitted(String) 判断是否拥有指定权限
		if(currentUser.isPermitted("winnebago:drive:eagle5")) {
			log.info("拥有指定权限");
		} else{
			log.info("当前用户没有指定权限");
		}
		
		// 退出登录
		currentUser.logout();
		System.exit(0);
		
	}
}
